<?php


namespace services\clinic;


use common\models\patient\UserAttr;
use common\models\rbac\UserRoom;
use insolita\migrik\resolver\RawColumnResolver;
use services\member\MemberService;
use Yii;
use common\models\base\BodyParts;
use common\models\patient\BodyParts as PatientBodyParts;
use common\models\patient\RevisitingRecord;
use services\common\ExcelExtendService;
use common\helpers\CommonHelper;
use common\models\clinic\Clinic;
use common\models\clinic\ProjectBind;
use common\models\clinic\TreatmentDelHistory;
use common\models\clinic\TreatmentRoom;
use common\models\clinic\UserSurplus;
use common\models\clinic\UserTreatment;
use common\models\clinic\UserTreatmentDetail;
use common\models\clinic\UserTreatmentWait;
use common\models\marketing\ClinicAssess;
use common\models\member\Member;
use common\models\patient\ClinicRecord;
use common\models\patient\OperateLog;
use common\models\patient\User;
use common\models\rbac\Menu;
use common\models\rbac\RolePermission;
use common\models\rbac\UserRole;
use common\components\Service;
use common\models\clinic\Project;
use common\models\member\Attr;
use yii\db\Exception;
use yii\db\Expression;
use yii\web\HttpException;

class TreatmentManageService extends Service
{

    /**
     * 诊疗记录
     *
     * @param $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
//    public  function getList($params, $page = 1, $pageSize = 10)
//    {
//        $query = Treatment::find()
//            ->select(['id','name', 'age', 'gender', 'clinic_project_name',new Expression('FROM_UNIXTIME(`clinic_time`, "%Y-%m-%d") clinic_time'),'clinic_name','patient_card_id'])
//            ->where([
//                'project_id' => $params['project_id'],
//                'status' => Treatment::STATUS_ENABLE,
//            ]);
//
//        // 关键词
//        if (isset($params['keywords']) && $params['keywords']) {
//            if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $params['keywords'], $match)) {
//                $query->andWhere(['like', 'name', "{$params['keywords']}%", false]);
//            } else {
//                $query->andWhere(['mobile' => trim($params['keywords'])]);
//            }
//        } else {
//            // 日期
//            if (isset($params['start_time']) && $params['start_time']) {
//                $query->andWhere(['>=', 'clinic_time', strtotime($params['start_time'])]);
//            }
//            if (isset($params['end_time']) && $params['end_time']) {
//                $query->andWhere(['<=', 'clinic_time', strtotime($params['end_time'] . ' 23:59:59')]);
//            }
//        }
//
//        // 诊室
//        isset($params['clinic_id']) && $params['clinic_id'] && $query->andWhere(['clinic_id' => $params['clinic_id']]);
//        // 治疗项目
//        isset($params['clinic_project_id']) && $params['clinic_project_id'] && $query->andWhere(['clinic_project_id' => $params['clinic_project_id']]);
//
//        // 总数
//        $total = $query->count();
//
//        // 分页
//        if ($page && $pageSize) {
//            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
//        }
//
//        $list = $query
//            ->orderBy(['created_at' => SORT_DESC, 'id' => SORT_DESC])
//            ->asArray()
//            ->all();
//
//        return [
//            'page' => (int)$page,
//            'pageSize' => (int)$pageSize,
//            'total' => (int)$total,
//            'list' => $list,
//        ];
//
//    }

    public function getList($params, $page = 1, $pageSize = 10)
    {
        $project_id = $params['project_id'];

        $query = UserTreatment::find()
            ->alias('t')
            ->leftJoin(User::tableName() . ' u', 'u.patient_card_id = t.patient_card_id and u.status = ' . User::STATUS_ENABLE)
            ->leftJoin(UserAttr::tableName() . ' ua', 'u.id = ua.patient_user_id')
            ->select(['t.id', 't.patient_card_id', 't.recently_clinic_num', 't.recently_surplus_num', 't.clinic_name', 't.operate_id', 't.operate_name', new Expression('FROM_UNIXTIME(`recently_clinic_time`, "%Y-%m-%d %H:%i") recently_clinic_time'),
                'u.name', 'u.age', 'u.gender', 'ua.in_hospital_status'
            ])
            ->where(['and',
                ['t.project_id' => $project_id],
                ['u.project_id' => $project_id],
                ['t.type' => UserTreatment::TYPE_TREAT]

            ]);

        $query->andWhere(['t.clinic_project_id' => $params['clinic_project_id']]);
        $query->andWhere(['t.treatment_room_id' => $params['treatment_room_id']]);

        // 筛选诊室
        isset($params['clinic_ids']) && !empty($params['clinic_ids']) && $query->andWhere(['u.clinic_id' => explode(',', $params['clinic_ids'])]);
        if (!isset($params['keywords']) || empty($params['keywords'])) {
            isset($params['time']) && !empty($params['time']) && $query->andWhere(['between', 't.recently_clinic_time', strtotime(date('Y-m-d', strtotime($params['time'])) . '00:00:00'), strtotime(date('Y-m-d', strtotime($params['time'])) . '23:59:59')]);
        } else {
            $query->andWhere(['or',
                ['t.patient_card_id' => $params['keywords']],
                ['like', 'u.name', $params['keywords']],
            ]);
        }

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['t.recently_clinic_time' => SORT_DESC, 'id' => SORT_DESC])
            ->asArray()
            ->all();

        // 获取该用户可以看得权限人员列表
        $operateArray = $this->operatorList($project_id);
        $operateList = isset($operateArray['attrArray']) ? array_column($operateArray['attrArray'], 'id') : array_column($operateArray, 'id');

        foreach ($list as &$value) {
            $value['modify'] = in_array($value['operate_id'], $operateList) ? true : false;
            $value['gender'] = User::$genders[$value['gender']];
            $value['num'] = $value['recently_clinic_num'] + $value['recently_surplus_num'];
        }

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];

    }


    /**
     * 左侧展示列表,治疗室->治疗项目
     * @param $project_id
     * @return array
     */
    public function treatmentRoomList($project_id)
    {
        $params['project_id'] = $project_id;
        // 查询结果
        $query = TreatmentRoom::find()
            ->select([
                'a.*',
                'GROUP_CONCAT(c.name) AS project_names',
                'GROUP_CONCAT(c.template) AS templates',
                'GROUP_CONCAT(c.id) AS ids',
                'GROUP_CONCAT(c.sort) AS sorts',
                'GROUP_CONCAT(c.created_at) AS created_at',
            ])
            ->alias('a')
            ->leftJoin(ProjectBind::tableName() . ' AS b', 'b.treatment_room_id = a.id')
            ->leftJoin(Project::tableName() . ' AS c', 'c.id = b.clinic_project_id')
            ->where([
                'a.status' => TreatmentRoom::STATUS_ENABLE,
                'a.project_id' => $project_id,
                'c.status' => Project::STATUS_ENABLE,
            ])
            ->groupBy('a.id');

        $data = $query
            ->orderBy(['a.sort' => SORT_ASC])
            ->asArray()
            ->all();
        $list = [];
        foreach ($data as &$row) {

            $row['expand'] = null;
            $projectNameStr = $row['project_names'] ? $row['project_names'] : '';
            if (strpos($projectNameStr, '308') !== false) {
                $row['expand'] = true;
            }

            $projectNamesArr = $row['project_names'] ? explode(',', $row['project_names']) : [];
            $projectIdsArr = $row['ids'] ? explode(',', $row['ids']) : [];
            $projectIdTempArr = $row['templates'] ? explode(',', $row['templates']) : [];
            $projectIdSortArr = $row['sorts'] ? explode(',', $row['sorts']) : [];
            $projectIdCreatedAtArr = $row['created_at'] ? explode(',', $row['created_at']) : [];

            $projectArray = [];
            foreach ($projectNamesArr as $key => &$value) {
                $projectArray[] = [
                    'title' => $value,
                    'id' => $projectIdsArr[$key],
                    'template' => $projectIdTempArr[$key],
                    'sort' => $projectIdSortArr[$key],
                    'created_at' => $projectIdCreatedAtArr[$key],
                ];
            }

            // 排序
            $keysSort = [];
            $keysCreatedAt = [];

            //排序按照数字从小到大排；1排在上面，9排在下面；如果排序号相同，后录入的治疗项目排在下面；
            foreach ($projectArray as $k => $v) {
                $keysSort[$k] = $v['sort'];
                $keysCreatedAt[$k] = $v['created_at'];
            }
            array_multisort($keysSort, SORT_ASC, $keysCreatedAt, SORT_ASC, $projectArray);

            $list[] = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'disabled' => true,
                'expand' => $row['expand'],
                'title' => $row['name'],
                'project_names_arr' => $projectArray,
                'status' => $row['status'],
            ];

        }

        return $list;

    }

    /**
     * 录入治疗列表
     * @param $params
     * @return array|\yii\db\ActiveRecord[]
     * @throws Exception
     */
    public function patientClinicList($params)
    {
        $project_id = $params['project_id'];
        $params['keywords'] = trim($params['keywords']);

        # 1. 查询用户
        $userArray = User::find()
            ->alias('u')
            ->select(['u.patient_card_id', 'u.name', 'u.gender', 'u.mobile', 'u.age', 'a.assess_name'])
            ->leftJoin(ClinicAssess::tableName() . ' a', 'a.id = u.clinic_assess_id')
            ->where(['and',
                ['u.project_id' => $project_id],
                ['u.status' => User::STATUS_ENABLE]
            ])
            ->andWhere(['or',
                ['u.patient_card_id' => $params['keywords']],
                ['u.name' => $params['keywords']],
            ])
            ->asArray()
            ->all();

        $cardIds = array_column($userArray, 'patient_card_id');

        # 2. 查询用户当前 治疗项目剩余
        $querySurplus = UserSurplus::find()
            ->select('patient_card_id, help_num, total_num')
            ->where(['patient_card_id' => $cardIds, 'project_id' => $project_id, 'clinic_project_id' => $params['clinic_project_id']])
            ->asArray()
            ->all();

        $surplusArray = array_column($querySurplus, null, 'patient_card_id');

        # 3. 查询最近一次治疗信息
        $queryOrder = UserTreatment::find()
            ->select(['patient_card_id', 'recently_clinic_num', 'recently_surplus_num', new Expression('FROM_UNIXTIME(`recently_clinic_time`, "%Y-%m-%d %H:%i") recently_clinic_time')])
            ->where(['and',
                ['project_id' => $project_id],
                ['clinic_project_id' => $params['clinic_project_id']],
                ['patient_card_id' => $cardIds],
                ['type' => UserTreatment::TYPE_TREAT]
            ])
            ->orderBy(['recently_clinic_time' => SORT_DESC, 'id' => SORT_DESC])
            ->limit(1000000)->createCommand()->getRawSql();

        // 查询用户最新一次该项目的治疗时间
        $sql = 'SELECT patient_card_id,recently_clinic_time,recently_clinic_num,recently_surplus_num FROM (' . $queryOrder . ') as e GROUP BY patient_card_id ';
        // 查询最近一百万条消费记录中,有没有变更诊室的

        $timeData = Yii::$app->db->createCommand($sql)->queryAll();

        $timeData = array_column($timeData, null, 'patient_card_id');

        // 获取治疗模板是否是301
        $clinicTemplate = Project::find()
            ->select('template')
            ->where(['id' => $params['clinic_project_id']])
            ->scalar();
        # 4. 合并数据
        foreach ($userArray as &$item) {
            if ($clinicTemplate == Project::TEMPLATE_308 || $clinicTemplate == Project::TEMPLATE_NAJIN) {
                $item['treatment_detail'] = $this->treatmentDetailByPCD($item['patient_card_id'], $params['clinic_project_id'], $project_id);
            } else {
                $item['treatment_detail'] = [];
            }
            $value = $timeData[$item['patient_card_id']] ?? [];
            $item['recently_clinic_time'] = $value['recently_clinic_time'] ?? '';
            $item['recently_clinic_num'] = (int)($value['recently_clinic_num'] ?? 0);
            $item['recently_surplus_num'] = (int)($value['recently_surplus_num'] ?? 0);
            $item['total_num'] = (int)($surplusArray[$item['patient_card_id']]['total_num'] ?? 0);
            $item['help_num'] = (int)($surplusArray[$item['patient_card_id']]['help_num'] ?? 0);
            $item['gender'] = User::$genders[$item['gender']];
        }

        return $userArray;

    }

    /**
     * 治疗详情
     * @param int $patient_card_id
     * @param $clinic_project_id
     * @param $project_id
     * @return array|\yii\db\ActiveRecord|null
     * @author chenyuebin
     */
    public function treatmentDetailByPCD($patient_card_id, $clinic_project_id, $project_id)
    {
        // 获取诊疗表id
        $clinicTreatmentId = UserTreatment::find()
            ->select('id')
            ->where([
                'and',
                ['patient_card_id' => $patient_card_id],
                ['project_id' => $project_id],
                ['clinic_project_id' => $clinic_project_id],
                ['type' => UserTreatment::TYPE_TREAT]
            ])
            ->orderBy('recently_clinic_time desc')
            ->asArray()
            ->one();
        // 获取诊疗记录
        $detail = [];
        if ($clinicTreatmentId) {
            $detail = UserTreatmentDetail::find()
                ->select(['num', 'dose', 'body_parts_large_name', 'body_parts_small_name', 'id'])
                ->where([
                    'and',
                    ['patient_card_id' => $patient_card_id],
                    ['clinic_treatment_id' => $clinicTreatmentId['id']]
                ])
                ->orderBy('created_at desc')
                ->asArray()
                ->all();
            foreach ($detail as $key => $value) {
                if ($value['num']) {
                    $detail[$key]['num'] = (int)$value['num'];
                }
                if ($value['dose']) {
                    $detail[$key]['dose'] = (int)$value['dose'];
                }
            }
            // 根据患者治疗详情id正序
            $detailIds = array_column($detail, 'id');
            array_multisort($detailIds, SORT_ASC, $detail);
        }

        return $detail;
    }

    /**
     * 添加治疗项目
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function addTreatment($params)
    {
        $project_id = $params['project_id'];
        $patient_card_id = $params['patient_card_id'];
        $time = strtotime($params['time']);
        $endTime = strtotime(date("Y-m-d" . '23:59:59'));
        $startTime = $endTime - 24 * 60 * 60 * 3;

        if ($time > $endTime || $time < $startTime) {
            return false; // 不在时间范围内
        }

        $insertData = [];
        $insertItem = [
            'project_id', 'patient_card_id', 'body_parts_large_name', 'body_parts_small_name', 'num', 'dose', 'created_at', 'updated_at', 'clinic_treatment_id'
        ];
        $num = 0;

        # 1. 整合导入不同模板的信息以及消耗的数量

        // 处理不同模板
        if ($params['template'] == Project::TEMPLATE_308 || $params['template'] == Project::TEMPLATE_NAJIN) { //308及纳金
            $content = json_decode($params['content']);

            foreach ($content as $item) {

                if (empty($item->body_parts_large_name) && empty($item->body_parts_small_name) && empty($item->num) && empty($item->dose)) {
                    continue; // 全部为空,
                }

                if (empty($item->body_parts_large_name) || empty($item->body_parts_small_name)) {
                    return false; // 存在有空的不会录入
                }

                if ($item->num <= 0) {
                    return false;
                }

                $num += abs($item->num);
                $insertData[] = [
                    'project_id' => $project_id,
                    'patient_card_id' => $patient_card_id,
                    'body_parts_large_name' => $item->body_parts_large_name,
                    'body_parts_small_name' => $item->body_parts_small_name,
                    'num' => abs($item->num),
                    'dose' => $item->dose,
                    'created_at' => time(),
                    'updated_at' => time()
                ];
            }

        } else {

            $validation = [];
            if ($params['template'] == Project::TEMPLATE_311) { // 311

                $validation = [
                    'dose'
                ];

            } elseif ($params['template'] == Project::TEMPLATE_HALF_311) { // 半仓311
                $validation = [
                    'dose',
                    'body_parts_large_name'
                ];

                // 半仓311 数量默认是1
                $params['num'] = 1;
            } elseif ($params['template'] == Project::TEMPLATE_TIME) { // 治疗时间
                $validation = [
                    'dose'
                ];
            }

            if ($params['num'] <= 0) {
                return false;
            }

            $num = abs($params['num']);

            foreach ($validation as $value) {

                if (!isset($params[$value]) && empty($params[$value])) {
                    return false; // 缺少参数
                }
            }

            $insertData[] = [
                'project_id' => $project_id,
                'patient_card_id' => $patient_card_id,
                'body_parts_large_name' => $params['body_parts_large_name'] ?? '',
                'body_parts_small_name' => '',
                'num' => abs($num),
                'dose' => $params['dose'] ?? '',
                'created_at' => time(),
                'updated_at' => time()
            ];

        }

        # 2. 获取治疗项目实际剩余数量
        $tr = Yii::$app->db->beginTransaction();
        try {
//            $surplusModel = UserSurplus::find()
//                ->where(['and',
//                    ['project_id' => $project_id],
//                    ['patient_card_id' => $patient_card_id],
//                    ['clinic_project_id' => $params['clinic_project_id']],
//                ])
//                ->one();

            // 没有明确主键,这个是表级别锁
            $surplusModel = UserSurplus::find()
                ->where("project_id = $project_id and patient_card_id = '$patient_card_id' and clinic_project_id = $params[clinic_project_id] for update")
                ->one();

            if (!$surplusModel) {
                $clinicModel = Project::findOne($params['clinic_project_id']);
                $surplusModel = new UserSurplus();
                $surplusModel->project_id = $project_id;
                $surplusModel->patient_card_id = $patient_card_id;
                $surplusModel->clinic_project_id = $params['clinic_project_id'];
                $surplusModel->clinic_project_name = $clinicModel->name;
                $surplusModel->total_num = 0;
                $surplusModel->help_num = 0;

            }

            $total_num = $surplusModel->total_num;
            $help_num = $surplusModel->help_num;

            // 消耗的数量优先减正常,正常减完在减援助
            // 剩余总数够扣的情况下
            if ($total_num + $help_num - $num > 0) {
                $s_total_num = $total_num > $num ? $total_num - $num : 0;
                $s_help_num = $s_total_num > 0 ? $help_num : $total_num + $help_num - $num;
                $recently_clinic_num = $s_total_num > 0 ? $num : $total_num;
                $recently_surplus_num = $s_total_num > 0 ? 0 : $num - $total_num;
            } else {
                // 正常剩余的总数
                $s_total_num = $total_num + $help_num - $num;
                $s_help_num = 0;
                // 使用
                $recently_clinic_num = $num - $help_num;
                $recently_surplus_num = $help_num;
            }


            // 查询操作人id和操作人名称
            $operate_id = $params['operate_id'];
            $operateArray = Member::find()
                ->select('m.realname,a.profession_name')
                ->alias('m')
                ->leftJoin(Attr::tableName() . ' a', 'a.member_id = m.id and a.project_id = ' . $project_id)
                ->where(['m.id' => $operate_id])
                ->asArray()
                ->one();

            $patientUser = User::find()
                ->select('c.name,u.id,c.sort,c.id as clinic_id')
                ->alias('u')
                ->leftJoin(Clinic::tableName() . ' c', 'c.id = u.clinic_id')
                ->where(['u.project_id' => $project_id, 'u.patient_card_id' => $patient_card_id, 'u.status' => User::STATUS_ENABLE])
                ->asArray()
                ->one();

            $model = new UserTreatment();
            $model->project_id = $project_id;
            $model->treatment_room_id = $params['treatment_room_id'];
            $model->patient_card_id = $patient_card_id;
            $model->clinic_project_id = $params['clinic_project_id'];
            $model->clinic_project_name = $surplusModel->clinic_project_name;
            $model->recently_clinic_time = strtotime($params['time']);
            $model->recently_clinic_num = $recently_clinic_num;
            $model->recently_surplus_num = $recently_surplus_num;
            $model->total_num = $s_total_num;
            $model->help_num = $s_help_num;
            $model->clinic_name = $patientUser['name'];
            $model->clinic_sort = $patientUser['sort'];
            $model->clinic_id = $patientUser['clinic_id'];
            $model->operate_id = $operate_id;
            $model->operate_profession = $operateArray['profession_name'] ?? '';
            $model->operate_name = $operateArray['realname'];
            $model->type = UserTreatment::TYPE_TREAT;
            $model->remark = $params['remark'] ?? '';
            $model->save();

            foreach ($insertData as &$item) {
                $item['clinic_treatment_id'] = $model->id;
            }
            Yii::$app->db->createCommand()->batchInsert(UserTreatmentDetail::tableName(), $insertItem, $insertData)->execute();
            $surplusModel->help_num = $s_help_num;
            $surplusModel->total_num = $s_total_num;
            $surplusModel->save();

            //记录治疗记录
            $operateArray = [
                'project_id' => $project_id,
                'patient_user_id' => $patientUser['id'],
                'action_type' => OperateLog::ACTION_TYPE_PATIENT_TREATMENT,
                'action_content' => '治疗项目:【' . $surplusModel->clinic_project_name . '】 本次治疗:【' . ($model->recently_clinic_num + $model->recently_surplus_num) . '】 本次剩余:【 ' . ($model->total_num + $model->help_num) . '】',
                'operate_name' => $operateArray['realname'],
                'operate_id' => $operate_id
            ];

            // 添加成功,抵消掉待办
            $waitArray = [
                'type' => $params['wait_type'] ?? 3,
                'project_id' => $project_id,
                'patient_card_id' => $patient_card_id,
                'clinic_project_id' => $model->clinic_project_id,
                'time' => $model->recently_clinic_time,
                'id' => $model->id,
            ];
            $this->changeWait($waitArray);

            $this->addOperateLog($operateArray);
            // 更新
            $this->updateUser($project_id, $model->patient_card_id, $model->clinic_id, $model->id, $model->recently_clinic_time, 'add');
            // 更新治疗部位到患者部位(业务部位) 仅限308 且不处理白白管家
            if (($params['template'] == Project::TEMPLATE_308 || $params['template'] == Project::TEMPLATE_NAJIN) && $project_id != 13) {
                $this->addPatientBodyPart($model->patient_card_id, $project_id, $model->id);
            }

            $tr->commit();

        } catch (Exception $e) {
            $tr->rollBack();
            return CommonHelper::api('422',$e->getMessage());
        }

        return true;

    }

    /**
     * 修改治疗信息
     *
     * @param $params
     * @return bool
     */
    public function updateTreatment($params)
    {
        $time = strtotime($params['time']);
        $endTime = strtotime(date("Y-m-d" . '23:59:59'));
        $startTime = $endTime - 24 * 60 * 60 * 3;
        $project_id = $params['project_id'];

        if ($time > $endTime || $time < $startTime) {
            return false; // 不在时间范围内
        }

        $tr = Yii::$app->db->beginTransaction();
        try {
            $num = 0;
            // 处理不同模板
            if ($params['template'] == Project::TEMPLATE_308 || $params['template'] == Project::TEMPLATE_NAJIN) { //308
                $content = json_decode($params['content']);

                // 查询子类信息
                $detailIds = UserTreatmentDetail::find()->where(['clinic_treatment_id' => $params['id']])->column();
                $userTreatModel = UserTreatment::findOne($params['id']);

                foreach ($content as $item) {

                    if (empty($item->body_parts_large_name) && empty($item->body_parts_small_name) && empty($item->num) && empty($item->dose)) {
                        continue; // 全部为空,
                    }

                    if (empty($item->body_parts_large_name) || empty($item->body_parts_small_name)) {
                        return false; // 存在有空的不会录入
                    }

                    if ($item->num <= 0) {
                        return false;
                    }

                    $num += abs($item->num);

                    // 详细不为零 是 更新,为0是新增
                    if ($item->id > 0) {
                        $detailModel = UserTreatmentDetail::findOne($item->id);
                        $detailIds = array_diff($detailIds, [$item->id]);

                    } else {
                        $detailModel = new UserTreatmentDetail();
                        $detailModel->clinic_treatment_id = $params['id'];
                        $detailModel->project_id = $project_id;
                        $detailModel->patient_card_id = $userTreatModel->patient_card_id;
                    }

                    $detailModel->body_parts_large_name = (string)$item->body_parts_large_name;
                    $detailModel->body_parts_small_name = (string)$item->body_parts_small_name;
                    $detailModel->num = $item->num;
                    $detailModel->dose = (string)$item->dose;
                    $detailModel->save();
                }

                UserTreatmentDetail::deleteAll(['id' => $detailIds]);

            } else {

                $validation = [];
                if ($params['template'] == Project::TEMPLATE_311) { // 311

                    $validation = [
                        'dose'
                    ];

                } elseif ($params['template'] == Project::TEMPLATE_HALF_311) { // 半仓311
                    $validation = [
                        'dose',
                        'body_parts_large_name'
                    ];

                    // 半仓311 数量默认是1
                    $params['num'] = 1;
                } elseif ($params['template'] == Project::TEMPLATE_TIME) {
                    $validation = [
                        'dose',
                    ];
                }

                if ($params['num'] <= 0) {
                    return false;
                }

                $num = abs($params['num']);
                $detailModel = UserTreatmentDetail::find()->where(['clinic_treatment_id' => $params['id']])->one();

                if (!$detailModel) {
                    $detailModel = new UserTreatmentDetail();
                    $detailModel->clinic_treatment_id = $params['id'];
                }

                $detailModel->num = $num;

                foreach ($validation as $value) {

                    if (!isset($params[$value]) && empty($params[$value])) {
                        return false; // 缺少参数
                    }

                    $detailModel->$value = $params[$value];
                }

                $detailModel->save();

            }

            // 更新操作人信息
            // 查询操作人id和操作人名称
            $operate_id = $params['operate_id'];
            $operateArray = Member::find()
                ->select('m.realname,a.profession_name')
                ->alias('m')
                ->leftJoin(Attr::tableName() . ' a', 'a.member_id = m.id and a.project_id = ' . $project_id)
                ->where(['m.id' => $operate_id])
                ->asArray()
                ->one();

            $model = UserTreatment::findOne($params['id']);
            $model->operate_id = $operate_id;
            $model->operate_profession = $operateArray['profession_name'] ?? '';
            $model->operate_name = $operateArray['realname'];
            $model->remark = $params['remark'] ?? '';
            $model->recently_clinic_time = strtotime($params['time']);

            // 处理数量问题
            $old_recently_clinic_num = $model->recently_clinic_num;
            $old_recently_surplus_num = $model->recently_surplus_num;
            $old_help_num = $model->help_num;
            $old_total_num = $model->total_num;

            $surplusModel = UserSurplus::find()
                ->where(['and',
                    ['project_id' => $model->project_id],
                    ['patient_card_id' => $model->patient_card_id],
                    ['clinic_project_id' => $model->clinic_project_id],
                ])
                ->one();

            $total_num = $surplusModel->total_num;
            $help_num = $surplusModel->help_num;
            // 修改后,与之前的差量
            $diff_num = $num - $old_recently_clinic_num - $old_recently_surplus_num;

            if ($diff_num > 0) { // 继续从剩余数量中扣

                if ($total_num + $help_num - $diff_num > 0) { // 目前剩余数量足够扣的
                    // 正常足够扣的 ? 只从正常扣 : 正常为零
                    $s_total_num = $total_num > $diff_num ? $total_num - $diff_num : 0;
                    // 正常足够扣的 ? 援助不变
                    $s_help_num = $s_total_num > 0 ? $help_num : $total_num + $help_num - $diff_num;
                    // 正常足够扣的 ? 消耗的正常为
                    $recently_clinic_num = $s_total_num > 0 ? $diff_num : $total_num;
                    $recently_surplus_num = $s_total_num > 0 ? 0 : $diff_num - $total_num;
                } else {
                    $s_total_num = $total_num + $help_num - $diff_num;  // 剩余数量不够扣的
                    $s_help_num = 0;
                    $recently_clinic_num = $diff_num - $help_num;
                    $recently_surplus_num = $help_num;
                }

                $model->recently_surplus_num = $old_recently_surplus_num + $recently_surplus_num;
                $model->recently_clinic_num = $old_recently_clinic_num + $recently_clinic_num;
                $model->help_num -= $recently_surplus_num;
                $model->total_num -= $recently_clinic_num;

                $surplusModel->help_num = $s_help_num;
                $surplusModel->total_num = $s_total_num;

            } elseif ($diff_num < 0) {  // 修改后消耗总数减少,还原数量

                // 有使用援助,优先恢复援助
                if ($old_recently_surplus_num - abs($diff_num) > 0) {
                    $s_total_num = $total_num;
                    $s_help_num = $help_num + abs($diff_num);
                    $recently_clinic_num = $old_recently_clinic_num;
                    $recently_surplus_num = $old_recently_surplus_num - abs($diff_num);

                } else { // 援助恢复完,恢复正常数量
                    // 恢复的正常数量
                    $add_total_num = abs($diff_num) - $old_recently_surplus_num;
                    $s_total_num = $total_num + $add_total_num;
                    $s_help_num = $help_num + $old_recently_surplus_num;
                    $recently_clinic_num = $old_recently_clinic_num - $add_total_num;
                    $recently_surplus_num = 0;
                }
                $model->recently_surplus_num = $recently_surplus_num;
                $model->recently_clinic_num = $recently_clinic_num;
                $model->help_num += $old_recently_surplus_num - $recently_surplus_num;
                $model->total_num += $old_recently_clinic_num - $recently_clinic_num;

                $surplusModel->help_num = $s_help_num;
                $surplusModel->total_num = $s_total_num;
            }

            //   $old_help_num = $model->help_num;
            //   $old_total_num = $model->total_num;

            $model->remark2 .= '使用数量(旧): ' . ($old_recently_clinic_num . '/' . $old_recently_surplus_num) . ' (新): ' . ($model->recently_clinic_num . '/' . $model->recently_surplus_num)
                . ' 剩余(旧)' . ($old_total_num . '/' . $old_help_num) . ' (新): ' . ($model->total_num . '/' . $model->help_num) . ' 编辑人:' . $model->operate_id . ' 修改时间' . date("Y-m-d H:i:s") . PHP_EOL;
            $model->save();
            $surplusModel->save();

            // 获取患者id
            $patientUser = User::find()->select('id')->where(['project_id' => $project_id, 'patient_card_id' => $model->patient_card_id, 'status' => User::STATUS_ENABLE])->asArray()->one();

            //记录治疗记录
            $operateArray = [
                'project_id' => $project_id,
                'patient_user_id' => $patientUser['id'],
                'action_type' => OperateLog::ACTION_TYPE_PATIENT_TREATMENT,
                'action_content' => '修改治疗项目信息:【 ' . $surplusModel->clinic_project_name . '】 本次治疗(改):【 ' . ($model->recently_clinic_num + $model->recently_surplus_num) . '】 本次剩余(改):【 ' . ($model->total_num + $model->help_num) . '】',
                'operate_name' => $operateArray['realname'],
                'operate_id' => $operate_id
            ];

            $this->addOperateLog($operateArray);
            // 更新 待修改
            $this->updateUser($project_id, $model->patient_card_id, $model->clinic_id, $model->id, $model->recently_clinic_time, 'update');

            $tr->commit();
        } catch (Exception $e) {
            $tr->rollBack();
            return false;
        }

        return true;
    }

    /**
     * 治疗详情
     * @param $params
     * @return array|bool|\yii\db\ActiveRecord|null
     */
    public function viewTreatment($params)
    {
        // 该条数据的诊疗详情
        $detail = UserTreatment::find()
            ->select(['u.name', 'u.age', 'u.gender', 'u.mobile', 't.patient_card_id', 't.clinic_project_id', 't.remark', 't.operate_id',
                'GROUP_CONCAT(d.id) AS ids', 'GROUP_CONCAT(d.body_parts_large_name) AS body_parts_large_names', 'GROUP_CONCAT(d.body_parts_small_name) AS body_parts_small_names',
                'GROUP_CONCAT(d.num) AS nums', 'GROUP_CONCAT(d.dose) AS dose'
            ])
            ->alias('t')
            ->leftJoin(UserTreatmentDetail::tableName() . ' d', 't.id = d.clinic_treatment_id')
            ->leftJoin(User::tableName() . ' u', 'u.patient_card_id = t.patient_card_id and u.project_id = ' . $params['project_id'] . ' and status = ' . User::STATUS_ENABLE)
            ->where(['t.id' => $params['id']])
            ->asArray()
            ->one();

        if (empty($detail)) {
            return false;
        }

        $newTreatment = UserTreatment::find()
            ->select([new Expression('FROM_UNIXTIME(`recently_clinic_time`, "%Y-%m-%d %H:%i") recently_clinic_time'), 't.recently_clinic_num', 't.recently_surplus_num', 's.total_num', 's.help_num'])
            ->alias('t')
            ->leftJoin(UserSurplus::tableName() . ' s', 's.project_id = t.project_id and s.patient_card_id = t.patient_card_id and s.clinic_project_id = t.clinic_project_id')
            ->where(['t.project_id' => $params['project_id'], 't.patient_card_id' => $detail['patient_card_id'], 't.clinic_project_id' => $detail['clinic_project_id']])
            ->orderBy(['t.recently_clinic_time' => SORT_DESC])
            ->limit(1)
            ->asArray()
            ->one();

        $idArray = explode(',', $detail['ids']);
        $largeArray = explode(',', $detail['body_parts_large_names']);
        $smallArray = explode(',', $detail['body_parts_small_names']);
        $numArray = explode(',', $detail['nums']);
        $doseArray = explode(',', $detail['dose']);
        unset($detail['ids'], $detail['body_parts_large_names'], $detail['body_parts_small_names'], $detail['nums'], $detail['dose']);
        $content = [];
        foreach ($idArray as $key => $item) {
            $content[] = [
                'id' => (int)($item ?? 0),
                'body_parts_large_name' => $largeArray[$key] ?? '',
                'body_parts_small_name' => $smallArray[$key] ?? '',
                'num' => (int)($numArray[$key] ?? 0),
                'dose' => (float)($doseArray[$key] ?? 0),
            ];
        }

        $detail = array_merge($detail, $newTreatment);
        $detail['content'] = $content;
        $detail['gender'] = User::$genders[$detail['gender']];
        // 查询改用户

        return $detail;

    }

    /**
     * 诊疗记录
     * @param $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function treatmentRecord($params, $page = 1, $pageSize = 10)
    {
        $project_id = $params['project_id'];

        $query = UserTreatment::find()
            ->alias('u')
            ->select(['u.patient_card_id', 'u.clinic_project_id', 'u.id', 'u.recently_clinic_num', 'u.recently_surplus_num', 'u.total_num', 'u.help_num', 'u.patient_signature', 'u.remark',
                'GROUP_CONCAT(d.id) AS ids', 'GROUP_CONCAT(d.body_parts_large_name) AS body_parts_large_names', 'GROUP_CONCAT(d.body_parts_small_name) AS body_parts_small_names',
                'GROUP_CONCAT(d.num) AS nums', 'GROUP_CONCAT(d.dose) AS dose',
                new Expression('FROM_UNIXTIME(`recently_clinic_time`, "%Y-%m-%d %H:%i") recently_clinic_time')
            ])
            ->innerJoin(UserTreatmentDetail::tableName() . ' d', 'u.id = d.clinic_treatment_id')
            ->where(['and',
                ['u.project_id' => $project_id],
                ['u.patient_card_id' => $params['patient_card_id']],
                ['u.clinic_project_id' => $params['clinic_project_id']],
                ['u.type' => UserTreatment::TYPE_TREAT]
            ])
            ->groupBy('d.clinic_treatment_id');


        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['u.recently_clinic_time' => SORT_DESC])
            ->asArray()
            ->all();

        foreach ($list as &$detail) {

            $idArray = explode(',', $detail['ids']);
            $largeArray = explode(',', $detail['body_parts_large_names']);
            $smallArray = explode(',', $detail['body_parts_small_names']);
            $numArray = explode(',', $detail['nums']);
            $doseArray = explode(',', $detail['dose']);
            unset($detail['ids'], $detail['body_parts_large_names'], $detail['body_parts_small_names'], $detail['nums'], $detail['dose']);
            $content = [];
            foreach ($idArray as $key => $item) {
                $content[] = [
                    'id' => (int)($item ?? 0),
                    'body_parts_large_name' => $largeArray[$key] ?? '',
                    'body_parts_small_name' => $smallArray[$key] ?? '',
                    'num' => (int)($numArray[$key] ?? 0),
                    'dose' => (int)($doseArray[$key] ?? 0),
                ];
            }

            if (!empty($detail['patient_signature'])) {
                $detail['patient_signature'] = env('SIGN_URL') . $detail['patient_signature'];
            }

            $detail['num'] = $detail['help_num'] + $detail['total_num'];
            $detail['recently_num'] = $detail['recently_surplus_num'] + $detail['recently_clinic_num'];

            // 根据患者治疗详情id正序
            $detailIds = array_column($content, 'id');
            array_multisort($detailIds, SORT_ASC, $content);

            $detail['content'] = $content;
        }


        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];

    }


    public function treatmentList($params, $page = 1, $pageSize = 10)
    {
        // 患者治疗列表
        $query = Treatment::find()
            ->select(['id', 'clinic_num', 'patient_signature', 'total_num', 'operate_name', 'operate_profession', 'clinic_project_name', new Expression('FROM_UNIXTIME(`clinic_time`, "%Y-%m-%d %H:%i") clinic_time'), 'clinic_name', 'patient_card_id'])
            ->where([
                'project_id' => $params['project_id'],
            ]);

        // 治疗项目
        isset($params['clinic_project_id']) && $params['clinic_project_id'] && $query->andWhere(['clinic_project_id' => $params['clinic_project_id']]);

        // 日期
        if (isset($params['start_time']) && $params['start_time']) {
            $query->andWhere(['>=', 'clinic_time', strtotime($params['start_time'])]);
        }
        if (isset($params['end_time']) && $params['end_time']) {
            $query->andWhere(['<=', 'clinic_time', strtotime($params['end_time'] . ' 23:59:59')]);
        }

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['created_at' => SORT_DESC, 'id' => SORT_DESC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];

    }

    public function newTreatment($params)
    {
        // 查询最近一次治疗信息
        $newTreatment = UserTreatment::find()
            ->select([new Expression('FROM_UNIXTIME(`recently_clinic_time`, "%Y-%m-%d %H:%i") recently_clinic_time'), 't.recently_clinic_num', 't.recently_surplus_num', 's.total_num', 's.help_num'])
            ->alias('t')
            ->leftJoin(UserSurplus::tableName() . ' s', 's.project_id = t.project_id and s.patient_card_id = t.patient_card_id and s.clinic_project_id = t.clinic_project_id')
            ->where(['t.project_id' => $params['project_id'], 't.patient_card_id' => $params['patient_card_id'], 't.clinic_project_id' => $params['clinic_project_id']])
            ->orderBy(['t.recently_clinic_time' => SORT_DESC])
            ->limit(1)
            ->asArray()
            ->one();

        // 查询治疗项目所属诊室
        $treatment_room = ProjectBind::find()
            ->alias('b')
            ->leftJoin(TreatmentRoom::tableName() . 'r', ' r.id = b.treatment_room_id')
            ->where([
                'r.status' => TreatmentRoom::STATUS_ENABLE,
                'b.clinic_project_id' => $params['clinic_project_id']
            ])
            ->one();

        $newTreatment['treatment_room_id'] = $treatment_room['treatment_room_id'];
        $newTreatment['recently_clinic_num'] = (int)($newTreatment['recently_clinic_num'] ?? 0);
        $newTreatment['recently_surplus_num'] = (int)($newTreatment['recently_surplus_num'] ?? 0);
        $newTreatment['recently_clinic_time'] = $newTreatment['recently_clinic_time'] ?? '';


        return $newTreatment;
    }

    /**
     * 统计,项目剩余总数
     *
     * @param $patient_card_id
     * @return array
     */
    public function clinicTotal($patient_card_id)
    {
        // 奕远系统过来的,项目购买总数
        $buyTotalArray = UserTreatmentProject::find()
            ->select(['clinic_project_id', 'clinic_project_name', 'total_num as sum', 'patient_card_id'])
            ->where([
                'patient_card_id' => $patient_card_id
            ])
            ->asArray()
            ->all();

        // pad端的消耗数
        $expenseTotalArray = Treatment::find()
            ->select(['sum(clinic_num) as sum', 'clinic_project_id', 'clinic_project_name'])
            ->where([
                'patient_card_id' => $patient_card_id
            ])
            ->groupBy(['clinic_project_id'])
            ->asArray()
            ->all();

        $buy_total_clinic_project_id = array_column($buyTotalArray, 'clinic_project_id');
        $expense_total_clinic_project_id = array_column($expenseTotalArray, 'clinic_project_id');
        $buyArray = array_column($buyTotalArray, null, 'clinic_project_id');
        $expenseArray = array_column($expenseTotalArray, null, 'clinic_project_id');
        $clinic_project_id_array = array_keys(array_flip($buy_total_clinic_project_id) + array_flip($expense_total_clinic_project_id));

        $data = [];
        foreach ($clinic_project_id_array as $value) {
            $temp = [];
            // 购买和消耗的数据里都存在项目
            if (isset($buyArray[$value]) && isset($expenseArray[$value])) {
                $temp['clinic_project_id'] = $buyArray[$value]['clinic_project_id'];
                $temp['clinic_project_name'] = $buyArray[$value]['clinic_project_name'];
                $temp['count'] = $buyArray[$value]['sum'] - $expenseArray[$value]['sum'];
            } elseif (!isset($buyArray[$value]) && isset($expenseArray[$value])) {
                $temp['clinic_project_id'] = $expenseArray[$value]['clinic_project_id'];
                $temp['clinic_project_name'] = $expenseArray[$value]['clinic_project_name'];
                $temp['count'] = 0 - $expenseArray[$value]['sum'];
            } elseif (isset($buyArray[$value]) && !isset($expenseArray[$value])) {
                $temp['clinic_project_id'] = $buyArray[$value]['clinic_project_id'];
                $temp['clinic_project_name'] = $buyArray[$value]['clinic_project_name'];
                $temp['count'] = $buyArray[$value]['sum'];
            }

            $data[] = $temp;
        }

        return $data;

    }

    /**
     * 治疗详情
     *
     * @param $id
     * @return array|\yii\db\ActiveRecord[]
     */
    public function treatmentDetail($id)
    {
        return TreatmentDetail::find()
            ->where(['clinic_treatment_id' => $id])
            ->asArray()
            ->all();
    }

    /**
     * 添加治疗记录
     * @param $params
     */
    public function addOperateLog(array $params)
    {
        $model = new OperateLog();
        $model->attributes = $params;
        $model->save();
    }

    /**
     * 更新上次治疗时间,更新上次到诊时间
     * @param $project_id
     * @param $patient_card_id
     * @param $clinic_id
     * @param $id
     * @param $clinic_time
     * @param $type
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function updateUser($project_id, $patient_card_id, $clinic_id, $id, $clinic_time, $type)
    {
        if ($type == 'add') {
            ExcelExtendService::toHospitalRecord($project_id, RevisitingRecord::TYPE_TREAT, $clinic_time, $patient_card_id, $clinic_id, $id);
        } elseif ($type == 'update') {
            ExcelExtendService::updateTreatRecord($id);
        } elseif ($type == 'delete') {
            ExcelExtendService::updateTreatRecord($id, true);
        }

        $userModel = User::find()
            ->where(['project_id' => $project_id, 'patient_card_id' => $patient_card_id, 'status' => User::STATUS_ENABLE])
            ->one();

        // 查询该用户最新治疗时间
        $new_clinic_time = UserTreatment::find()
            ->where(['project_id' => $project_id, 'patient_card_id' => $patient_card_id, 'type' => UserTreatment::TYPE_TREAT])
            ->orderBy(['recently_clinic_time' => SORT_DESC])
            ->asArray()
            ->one();

        // 最新治疗时间
        $last_clinic_time = $new_clinic_time['recently_clinic_time'];
        $userModel->last_clinic_time = $last_clinic_time;

        // 查询最近来院时间
        $last_revisiting_time = RevisitingRecord::find()
            ->where(['project_id' => $project_id, 'patient_card_id' => $patient_card_id])
            ->andWhere(['is_sum' => RevisitingRecord::IS_SUM_YES])
            ->orderBy(['revisting_time' => SORT_DESC])
            ->asArray()
            ->one();

        $revisiting_count = RevisitingRecord::find()
            ->where([
                'project_id' => $project_id,
                'patient_card_id' => $patient_card_id,
                'is_sum' => RevisitingRecord::IS_SUM_YES
            ])->count();

        $today = strtotime(date('Y-m-d', time()));
        $receptDay = strtotime(date('Y-m-d', $last_revisiting_time['revisting_time'] ?? $userModel->reg_time));
        //优先上次到院时间 - 挂号时间
        $userModel->missed_days = ($today - $receptDay) / 86400;
        $userModel->revisiting_count = $revisiting_count;
        $userModel->last_revisiting_time = $receptDay;
        $userModel->save();

        return true;

    }

    // 操作者列表
    public function operatorList($project_id)
    {
        // 查询操作人id和操作人名称
        $member = Yii::$app->user->identity->member;
        $attrModel = Attr::find()
            ->where(['and',
                ['member_id' => $member->id],
                ['!=', 'is_department_leader', Attr::IS_DEPARTMENT_LEADER_NO],
                ['project_id' => $project_id]
            ])
            ->one();

        // 如果不是 负责人,展示该用户自己
        if (!$attrModel) {
            $attrArray[] = [
                'id' => $member->id,
                'realname' => $member->realname
            ];
            return $attrArray;
        }

        $query = Attr::find()
            ->select('m.id,m.realname')
            ->alias('a')
            ->innerJoin(Member::tableName() . ' m', ' a.member_id = m.id')
            ->innerJoin(UserRole::tableName() . ' r', ' r.member_id = m.id')
            ->where(['and',
                ['a.project_id' => $project_id],
                ['m.status' => Member::STATUS_ENABLE],
                ['!=', 'a.member_id', $member->id]
            ]);

        // 要展示所有有权限的
        $roles = RolePermission::find()
            ->select('role_id')
            ->where(['project_id' => [$project_id, 0], 'permission_id' => Menu::MENU_TREATMENT_LIST, 'permission_type' => RolePermission::PERMISSION_TYPE_MENU])
            ->column();

        $query->andWhere(['r.role_id' => $roles]);


        if ($attrModel->is_department_leader == Attr::IS_DEPARTMENT_LEADER_YES) {
            $query->andWhere(['a.department_id' => $attrModel->department_id]);
        }

        $query->groupBy('m.id');

        $attrArray = $query
            ->asArray()
            ->all();

        // 如果是项目负责人,该用户展示
        array_unshift($attrArray, [
            'id' => $member->id,
            'realname' => $member->realname
        ]);

        return [
            'attrArray' => $attrArray,
            'operatorId' => $member->id
        ];
    }

    // 记录
    public function clinicList($params)
    {
        $project_id = $params['project_id'];
        $member_id = Yii::$app->user->identity->member_id;

        if (isset($params['day']) && !empty($params['day'])) {
            $day = $params['day'];
        } else {
            $day = date('Y-m-d');
        }

        $start_time = strtotime($day . '00:00:00');
        $end_time = strtotime($day . '23:59:59');

        $userInfo = User::find()
            ->select(['u.age', 'u.gender', 'u.name', 'u.patient_card_id', 'GROUP_CONCAT(w.clinic_project_id) as clinic_project_ids'])
            ->alias('u')
            ->leftJoin(UserTreatmentWait::tableName() . ' w', ' u.patient_card_id = w.patient_card_id and w.project_id =' . $project_id . ' and w.status = ' . UserTreatmentWait::STATUS_WAIT
                . ' and w.created_at BETWEEN ' . $start_time . ' and ' . $end_time)
            ->where([
                'and',
                ['u.project_id' => $project_id],
                ['u.status' => User::STATUS_ENABLE],
            ])
            ->andWhere([
                'or',
                ['u.patient_card_id' => $params['patient_card_id']],   # patient_card_id 代替 keywords  可以搜索 手机号,姓名,诊疗号
                ['u.mobile' => $params['patient_card_id']],
                ['u.name' => $params['patient_card_id']]
            ])
            ->groupBy(['u.id'])
            ->orderBy(['u.created_at' => SORT_DESC])
            ->asArray()
            ->all();

        if (!$userInfo) {
            return CommonHelper::api(422, '请核对查询信息,没有该患者信息');
        }

        $roomArray = [];
        // 获取用户诊疗室 权限
        $room_id = MemberService::getRoomIdByMemberId($member_id, $project_id);
        $room_name = $room_id ? MemberService::getRoomName($room_id) : [];
        !empty($room_name) && $roomArray = array_combine($room_id, explode(',', $room_name));

        $projectArray = Project::find()
            ->alias('p')
            ->select(['p.name as project_name', 'b.clinic_project_id', 'p.template', 'b.treatment_room_id', 'b.id'])
            ->innerJoin(ProjectBind::tableName() . ' b', 'b.clinic_project_id = p.id')
            ->where([
                'and',
                ['p.project_id' => $project_id],
                ['p.status' => Project::STATUS_ENABLE],
                ['b.treatment_room_id' => $room_id]
            ])
            ->orderBy(['p.sort' => SORT_ASC, 'p.created_at' => SORT_ASC])
            ->asArray()
            ->all();

        $temp = [];
        foreach ($projectArray as $item) {
            $temp[$item['treatment_room_id']][] = $item;
        }

        $projectRoom = [];
        foreach ($temp as $key => $item) {

            $projectRoom[] = [
                'room_id' => $key,
                'room_name' => $roomArray[$key] ?? '',
                'children' => $item
            ];
        }

        // 处理用户下面的权限
        $tableList = '';
        foreach ($userInfo as &$item) {
            empty($tableList) ? $tableList = $item['patient_card_id'] : '';
            $item['gender'] = User::$genders[$item['gender']];
            $item['clinic_project_ids'] = $item['clinic_project_ids'] ? explode(',', $item['clinic_project_ids']) : [];
            $item['projectArray'] = $projectRoom ?? [];
        }

        $data = [
            'list' => $userInfo,
            'tableList' => $tableList
        ];

        return $data;

    }

    /**
     * 添加待录入记录
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function addClinicWait($params)
    {
        $project_id = $params['project_id'];
        $patient_card_id = $params['patient_card_id'];

        if (isset($params['day']) && !empty($params['day'])) {
            $day = $params['day'];
        } else {
            $day = date('Y-m-d');
        }

        $diff_time_start = time();

        $start_time = strtotime($day . '00:00:00');
        $end_time = strtotime($day . '23:59:59');

        $time1 = time();
        $diff_time_start .= '  1:' . ($time1 - $diff_time_start) . '   ';

        // 获取 指定时间内的 待治疗记录
        $waitArray = UserTreatmentWait::find()
            ->select('clinic_project_id,status')
            ->where([
                'and',
                ['patient_card_id' => $patient_card_id],
                ['between', 'created_at', $start_time, $end_time],
                ['project_id' => $project_id]
            ])
            ->andWhere([
                'or',
                ['status' => UserTreatmentWait::STATUS_WAIT],
                ['status' => UserTreatmentWait::STATUS_DELETE]
            ])
            ->asArray()
            ->all();

        $time2 = time();
        $diff_time_start .= '  2:' . ($time2 - $time1) . '   ';

        $clinic_project_id = explode(',', $params['clinic_project_id']);

        // 查询,要添加的
        $clinic_project_id_Array = Project::find()
            ->select(['id', 'template', 'name'])
            ->where([
                'and',
                ['project_id' => $project_id],
                ['status' => Project::STATUS_ENABLE],
                ['id' => $clinic_project_id]
            ])
            ->asArray()
            ->all();
        $clinic_project_id_Array = array_column($clinic_project_id_Array, null, 'id');

        $time3 = time();
        $diff_time_start .= '  3:' . ($time3 - $time2) . '   ';

        $waitArray = array_column($waitArray, null, 'clinic_project_id');
        $insertData = [];
        $restoreArray = [];

        $member = Yii::$app->user->identity->member;

        // 判断
        foreach ($clinic_project_id_Array as $key => $item) {

            // 待录入记录中没有的重新插入
            if (!isset($waitArray[$key])) {
                $insertData[] = [
                    'project_id' => $project_id,
                    'patient_card_id' => $patient_card_id,
                    'clinic_project_id' => $key,
                    'clinic_project_name' => $item['name'],
                    'operate_id' => $member->id,
                    'operate_name' => $member->username,
                    'template' => $item['template'],
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
            } elseif ($waitArray[$key]['status'] == UserTreatmentWait::STATUS_DELETE) { // 待录入记录中是-1变成0
                // 之前是删除状态的,恢复删除状态
                $restoreArray[] = $key;
            }

            unset($waitArray[$key]);

        }

        $time4 = time();
        $diff_time_start .= '  4:' . ($time4 - $time3) . '   ';

        // 添加带诊疗记录
        Yii::$app->db->createCommand()->batchInsert(
            UserTreatmentWait::tableName(),
            ['project_id', 'patient_card_id', 'clinic_project_id', 'clinic_project_name', 'operate_id', 'operate_name', 'template', 'created_at', 'updated_at'],
            $insertData
        )->execute();

        $time5 = time();
        $diff_time_start .= '  5:' . ($time5 - $time4) . '   ';

        // 删除
        UserTreatmentWait::updateAll(['status' => UserTreatmentWait::STATUS_DELETE], ['and',
            ['project_id' => $project_id],
            ['patient_card_id' => $patient_card_id],
            ['between', 'created_at', $start_time, $end_time],
            ['clinic_project_id' => array_keys($waitArray)],
            ['status' => UserTreatmentWait::STATUS_WAIT]
        ]);

        // 恢复状态 0 => 1
        UserTreatmentWait::updateAll(['status' => UserTreatmentWait::STATUS_WAIT], ['and',
            ['project_id' => $project_id],
            ['patient_card_id' => $patient_card_id],
            ['between', 'created_at', $start_time, $end_time],
            ['clinic_project_id' => $restoreArray],
            ['status' => UserTreatmentWait::STATUS_DELETE]
        ]);

        $time6 = time();
        $diff_time_start .= '  6:' . ($time6 - $time5) . PHP_EOL;

        if (file_exists('notify.txt')) {
            //"当前目录中，文件存在"，追加
            $myfile = fopen("notify.txt", "a") or die("Unable to open file!");
        } else {
            //"当前目录中，文件不存在",新写入
            $myfile = fopen("notify.txt", "w") or die("Unable to open file!");
        }

        fwrite($myfile, $diff_time_start);
        //记得关闭流
        fclose($myfile);

        return true;
    }

    /**
     * 待录入治疗列表,已录入治疗列表
     */
    public function waitList($params, $page = 1, $pageSize = 8)
    {
        $project_id = $params['project_id'];

        if (isset($params['day']) && !empty($params['day'])) {
            $day = $params['day'];
        } else {
            $day = date('Y-m-d');
        }

        $start_time = strtotime($day . '00:00:00');
        $end_time = strtotime($day . '23:59:59');

        //  查询用户能看到的治疗项目
        $clinic_project_id = UserRoom::find()
            ->select('b.clinic_project_id')
            ->alias('a')
            ->leftJoin(ProjectBind::tableName() . ' b', 'b.treatment_room_id = a.room_id')
            ->where([
                'a.project_id' => $project_id,
                'a.member_id' => Yii::$app->user->identity->member_id
            ])
            ->column();

        # 1. 待录入列表
        $waitQuery = User::find()
            ->select(['u.age', 'u.name', 'u.gender', 'u.patient_card_id', 'w.clinic_project_id', 'w.clinic_project_name', 'p.total_num', 'p.help_num', 'w.template', 'c.name as clinic_name'])
            ->alias('u')
            ->innerJoin(UserTreatmentWait::tableName() . ' w', ' u.patient_card_id = w.patient_card_id and w.project_id =' . $project_id . ' and w.status = ' . UserTreatmentWait::STATUS_WAIT
                . ' and w.created_at BETWEEN ' . $start_time . ' and ' . $end_time)
            ->leftJoin(UserSurplus::tableName() . ' p', 'p.patient_card_id = w.patient_card_id and p.clinic_project_id = w.clinic_project_id and p.project_id =' . $project_id)
            ->leftJoin(Clinic::tableName() . ' c', 'c.id = u.clinic_id')
            ->where([
                'and',
                ['u.project_id' => $project_id],
                ['u.status' => User::STATUS_ENABLE],
                ['w.clinic_project_id' => $clinic_project_id]
            ]);


        if (isset($params['keyword']) && !empty($params['keyword'])) {
            $waitQuery->andWhere([
                'or',
                ['u.patient_card_id' => $params['keyword']],
                ['u.name' => $params['keyword']]
            ]);
        }

        if (isset($params['clinic_project_id']) && !empty($params['clinic_project_id'])) {
            $waitQuery->andWhere(['w.clinic_project_id' => $params['clinic_project_id']]);
        }
        //    $total = $waitQuery->count();
        $wait_total = $waitQuery->count();

        // 分页
        if ($page && $pageSize) {
            $waitQuery->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $waitList = $waitQuery
            ->orderBy(['w.created_at' => SORT_DESC, 'w.id' => SORT_DESC])
            ->asArray()
            ->all();

        foreach ($waitList as &$item) {
            $item['help_num'] = $item['help_num'] ?? '0';
            $item['total_num'] = $item['total_num'] ?? '0';
            $item['gender'] = User::$genders[$item['gender']];

        }

        return [
            'page' => $page,
            'pageSize' => $pageSize,
            'total' => $wait_total,
            'wait_total' => $wait_total,
            'waitList' => $waitList,
        ];

    }

    /**
     * 已录入
     * @param $params
     * @return array
     */
    public function entryList($params, $page = 1, $pageSize = 8)
    {

        $project_id = $params['project_id'];

        if (isset($params['day']) && !empty($params['day'])) {
            $day = $params['day'];
        } else {
            $day = date('Y-m-d');
        }

        $start_time = strtotime($day . '00:00:00');
        $end_time = strtotime($day . '23:59:59');

        # 2. 已录入列表
        $treatmentQuery = User::find()
            ->select(['t.id', 'u.age', 'u.name', 'u.gender', 'u.patient_card_id', 't.clinic_project_name', 't.operate_name', 't.operate_id', 'FROM_UNIXTIME(t.recently_clinic_time, "%Y-%m-%d %H：%i") recently_clinic_time', 't.clinic_project_id', 't.recently_surplus_num',
                't.recently_clinic_num', 'c.name as clinic_name', 'p.template'])
            ->alias('u');

        if (empty($start_time) || empty($end_time)) {
            $treatmentQuery->innerJoin(UserTreatment::tableName() . ' t', ' u.patient_card_id = t.patient_card_id and t.project_id =' . $project_id);

        } else {
            $treatmentQuery->innerJoin(UserTreatment::tableName() . ' t', ' u.patient_card_id = t.patient_card_id and t.project_id =' . $project_id
                . ' and t.recently_clinic_time BETWEEN ' . $start_time . ' and ' . $end_time);
        }

        $treatmentQuery->leftJoin(Clinic::tableName() . ' c', 'c.id = u.clinic_id')
            ->leftJoin(Project::tableName() . ' p', ' p.id = t.clinic_project_id')
            ->where([
                'and',
                ['u.project_id' => $project_id],
                ['u.status' => User::STATUS_ENABLE],
                ['t.type' => UserTreatment::TYPE_TREAT]
            ]);


        if (isset($params['keyword']) && !empty($params['keyword'])) {
            $treatmentQuery->andWhere([
                'or',
                ['u.patient_card_id' => $params['keyword']],
                ['u.name' => $params['keyword']]
            ]);
        }

        if (isset($params['clinic_project_id']) && !empty($params['clinic_project_id'])) {
            $treatmentQuery->andWhere(['t.clinic_project_id' => $params['clinic_project_id']]);
        }

        $treatment_total = $treatmentQuery->count();

        // 分页
        if ($page && $pageSize) {
            $treatmentQuery->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $treatmentList = $treatmentQuery
            ->orderBy(['t.created_at' => SORT_DESC, 't.id' => SORT_DESC])
            ->asArray()
            ->all();

        // 获取该用户可以看得权限人员列表
        $operateArray = $this->operatorList($project_id);
        $operateList = isset($operateArray['attrArray']) ? array_column($operateArray['attrArray'], 'id') : array_column($operateArray, 'id');

        foreach ($treatmentList as &$item) {
            $item['modify'] = in_array($item['operate_id'], $operateList) ? true : false;
            $item['all_num'] = $item['recently_surplus_num'] + $item['recently_clinic_num'];
            $item['gender'] = User::$genders[$item['gender']];
        }

        return [
            'page' => $page,
            'pageSize' => $pageSize,
            'treatment_total' => $treatment_total,
            'treatmentList' => $treatmentList
        ];

    }

    /**
     * 可以撤销当天内,最新一条的记录
     */
    public function revocationTreatment($params)
    {
        $treatmentModel = UserTreatment::find()
            ->where(['id' => $params['id'], 'project_id' => $params['project_id'], 'type' => UserTreatment::TYPE_TREAT])
            ->one();

        //判断,需要撤销的记录是不是当前最新的记录
        $newTreatment = UserTreatment::find()
            ->where([
                'and',
                ['patient_card_id' => $treatmentModel->patient_card_id],
                ['project_id' => $treatmentModel->project_id],
                ['clinic_project_id' => $treatmentModel->clinic_project_id],
                ['type' => UserTreatment::TYPE_TREAT]
            ])
            ->orderBy(['created_at' => SORT_DESC])
            ->limit(1)
            ->asArray()
            ->one();

        $detailArray = UserTreatmentDetail::find()
            ->where(['clinic_treatment_id' => $newTreatment['id']])
            ->asArray()
            ->all();

        if ($treatmentModel->id != $newTreatment['id']) {
            return CommonHelper::api(422, '不是最新治疗,不可撤销');
        }

        // 恢复数量
        $tr = Yii::$app->db->beginTransaction();
        try {
            // 查询该项目剩余的数量
            $surplusModel = UserSurplus::find()
                ->where([
                    'and',
                    ['project_id' => $params['project_id']],
                    ['patient_card_id' => $treatmentModel->patient_card_id],
                    ['clinic_project_id' => $treatmentModel->clinic_project_id]
                ])
                ->one();

            $surplusModel->total_num += $newTreatment['recently_clinic_num'];
            $surplusModel->help_num += $newTreatment['recently_surplus_num'];
            $surplusModel->save();

            // 获取需要删除的信息,存入记录中
            $hisModel = new TreatmentDelHistory();
            $hisModel->del_treatment_detail_id = implode(',', array_column($detailArray, 'id'));
            $hisModel->del_treatment_id = $newTreatment['id'];
            $hisModel->patient_card_id = $treatmentModel->patient_card_id;
            $hisModel->name = $surplusModel->name;
            $hisModel->project_id = $params['project_id'];
            $hisModel->clinic_project_id = $treatmentModel->clinic_project_id;
            $hisModel->json_str = json_encode($newTreatment);
            $hisModel->json_str_detail = json_encode($detailArray);
            $hisModel->save();

            // 删除最新,添加的项目
            self::updateUser($newTreatment['project_id'], $newTreatment['patient_card_id'], $newTreatment['clinic_id'], $newTreatment['id'], $newTreatment['recently_clinic_time'], 'delete');
            UserTreatment::deleteAll(['id' => $newTreatment['id']]);
            UserTreatmentDetail::deleteAll(['clinic_treatment_id' => $newTreatment['id']]);

            $tr->commit();
        } catch (Exception $e) {
            $tr->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }

        return true;
    }

    /**
     * 添加治疗记录成功,改变,待录入状态
     * @param $params
     * @return bool
     */
    public function changeWait($params)
    {

        // 查询,录入时间是不是,当天

        $start_time = strtotime(date('Y-m-d 00:00:00'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));

        if ($params['time'] < $start_time || $params['time'] > $end_time) {
            return false;
        }

        // 查询当天,待录入
        $waitModel = UserTreatmentWait::find()
            ->where([
                'and',
                ['between', 'created_at', $start_time, $end_time],
                ['project_id' => $params['project_id']],
                ['patient_card_id' => $params['patient_card_id']],
                ['clinic_project_id' => $params['clinic_project_id']],
                ['status' => UserTreatmentWait::STATUS_WAIT]
            ])
            ->one();

        if (!$waitModel) {
            return false;
        }

        $waitModel->treatment_id = $params['id'];
        $waitModel->status = $params['type'];
        $waitModel->save();

        return true;

    }

    /**
     * @apiName 修复治疗信息,历史记录诊室id
     * @apiGroup
     * @author loujie
     */
    public function updateClinicId()
    {
        $clinicArray = UserTreatment::find()
            ->select('project_id,clinic_name')
            ->groupBy('project_id,clinic_name')
            ->asArray()
            ->all();

        foreach ($clinicArray as $item) {

            if (empty($item['clinic_name'])) {
                continue;
            }

            $clinicItem = Clinic::find()
                ->where([
                    'project_id' => $item['project_id'],
                    'name' => $item['clinic_name']
                ])
                ->orderBy(['status' => SORT_DESC])
                ->asArray()
                ->all();

            if (empty($clinicItem)) {
                continue;
            }

            $clinicId = $clinicItem[0]['id'];

            UserTreatment::updateAll(['clinic_id' => $clinicId], ['clinic_id' => 0, 'project_id' => $item['project_id'], 'clinic_name' => $item['clinic_name']]);

        }

        return true;

    }


    /**
     * @apiName 根据308治疗部位,同步患者部位信息
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @param null $start_time 根据时间段来获取308治疗部位
     * @param null $end_time
     * @throws Exception
     * @author loujie
     */
    public function treatmentPart($start_time = null, $end_time = null)
    {
        // 查询各个项目的308  && 不处理白白管家的项目
        $clinic_project_id = Project::find()
            ->select('id as clinic_project_id, project_id')
            ->where([
                'template' => [Project::TEMPLATE_308, Project::TEMPLATE_NAJIN],
                'status' => Project::STATUS_ENABLE
            ])
            ->andWhere(['!=', 'project_id', '13'])
            ->asArray()
            ->all();

        if (!empty($start_time) && !empty($end_time)) {
            $start = strtotime($start_time);
            $end = strtotime($end_time) + 86399;
        }

        // 获取所有部位
        $bodyArray = BodyParts::find()
            ->select('id, pid, body_parts_name')
            ->where(['status' => BodyParts::STATUS_ENABLE])
            ->asArray()
            ->all();

        $bodyArray = array_column($bodyArray, null, 'body_parts_name');

        ## 项目循环
        foreach ($clinic_project_id as $item) {

            //  echo 'project_id :' . $item['project_id'] . PHP_EOL;

            // 获取各个项目308
            $query = UserTreatment::find()
                ->select(['b.patient_card_id', 'GROUP_CONCAT(DISTINCT b.body_parts_large_name) as body_parts_large_name'])
                ->alias('a')
                ->leftJoin(UserTreatmentDetail::tableName() . ' as b', 'b.clinic_treatment_id = a.id')
                ->where([
                    'a.clinic_project_id' => $item['clinic_project_id'],
                    'a.project_id' => $item['project_id']
                ]);

            if (isset($start) && isset($end)) {
                $query->andWhere(['between', 'a.created_at', $start, $end]);
            }

            $userBody = $query->groupBy('b.patient_card_id')
                ->asArray()
                ->all();

            $patientCardArray = array_column($userBody, 'patient_card_id');

            // 查询患者业务部位
            $patientBodyArray = User::find()
                ->alias('a')
                ->select('a.id, a.patient_card_id, GROUP_CONCAT(b.body_parts_id) as body_parts_id, GROUP_CONCAT(b.status) as status')
                ->leftJoin(PatientBodyParts::tableName() . ' b', 'b.patient_user_id = a.id')
                ->where([
                    'a.status' => User::STATUS_ENABLE,
                    'a.project_id' => $item['project_id'],
                    'a.patient_card_id' => $patientCardArray,
                ])
                ->groupBy('a.id')
                ->asArray()
                ->all();

            $patientBodyArray = array_column($patientBodyArray, null, 'patient_card_id');


            ## 308对应的 患者循环
            foreach ($userBody as $body) {
                $this->treatmentUserPart($patientBodyArray, $body, $bodyArray);
            }

        }
    }

    /**
     * @param $patient_card_id
     * @param $project_id
     * @throws Exception
     * @author loujie
     * @api {post} ADDRESS
     * @apiName
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     */
    public function addPatientBodyPart($patient_card_id, $project_id, $treatment_id)
    {

        // bodyArray获取所有部位
        $bodyArray = BodyParts::find()
            ->select('id, pid, body_parts_name')
            ->where(['status' => BodyParts::STATUS_ENABLE])
            ->asArray()
            ->all();

        // bodyArray部位合集
        $bodyArray = array_column($bodyArray, null, 'body_parts_name');

        //patientBodyArray 患者业务部位
        $patientBodyArray = User::find()
            ->alias('a')
            ->select('a.id, a.patient_card_id, GROUP_CONCAT(b.body_parts_id) as body_parts_id, GROUP_CONCAT(b.status) as status')
            ->leftJoin(PatientBodyParts::tableName() . ' b', 'b.patient_user_id = a.id')
            ->where([
                'a.status' => User::STATUS_ENABLE,
                'a.project_id' => $project_id,
                'a.patient_card_id' => $patient_card_id,
            ])
            ->groupBy('a.id')
            ->asArray()
            ->all();

        $patientBodyArray = array_column($patientBodyArray, null, 'patient_card_id');

        // 治疗308的部位
        $userBody = UserTreatment::find()
            ->select(['b.patient_card_id', 'GROUP_CONCAT(DISTINCT b.body_parts_large_name) as body_parts_large_name'])
            ->alias('a')
            ->leftJoin(UserTreatmentDetail::tableName() . ' as b', 'b.clinic_treatment_id = a.id')
            ->where([
                'a.id' => $treatment_id,
            ])
            ->groupBy('b.patient_card_id')
            ->asArray()
            ->one();

        $this->treatmentUserPart($patientBodyArray, $userBody, $bodyArray);
    }


    /**
     * @apiGroup 具体到个人的治疗部位转数组
     * @apiParam {Number}
     * @apiParam {String}
     * @param $patientBodyArray
     * @param $body
     * @param $bodyArray
     * @throws Exception
     * @author loujie
     */
    public function treatmentUserPart($patientBodyArray, $body, $bodyArray)
    {
        if (isset($patientBodyArray[$body['patient_card_id']])) {
            // 业务部位,转数组
            $businessBody = explode(',', $patientBodyArray[$body['patient_card_id']]['body_parts_id']);
            // 业务部位,状态
            $businessBodyStatus = explode(',', $patientBodyArray[$body['patient_card_id']]['status']);

            // 治疗部位,转数组
            $clinicBody = explode(',', $body['body_parts_large_name']);

            $updateArray = [];
            $insertData = [];

            // 转化治疗部位,名称转换成一级部位id
            foreach ($clinicBody as $key => &$clinicBodyItem) {

                if (!isset($bodyArray[$clinicBodyItem])) {
                    unset($clinicBody['key']);
                    continue;
                }
                // 对比需要添加和需要改变状态的数据
                $clinicBodyId = $bodyArray[$clinicBodyItem]['pid'] ? $bodyArray[$clinicBodyItem]['pid'] : $bodyArray[$clinicBodyItem]['id'];
                $businessKey = array_search($clinicBodyId, $businessBody);
                // 业务部位不存在->直接添加,存在->status 状态 1 跳过,-1 状态置为 1
                if (is_numeric($businessKey)) {

                    if ($businessBodyStatus[$businessKey] == PatientBodyParts::STATUS_DELETE) {
                        $updateArray[] = $clinicBodyId;
                    }

                } else {
                    $insertData[] = [
                        'patient_user_id' => $patientBodyArray[$body['patient_card_id']]['id'],
                        'body_parts_id' => $clinicBodyId,
                        'status' => 1,
                        'created_at' => time(),
                        'updated_at' => time()
                    ];
                }
            }

            // 更新部位关联表
            !empty($updateArray) && PatientBodyParts::updateAll(['status' => PatientBodyParts::STATUS_ENABLE, 'updated_at' => time()], ['patient_user_id' => $patientBodyArray[$body['patient_card_id']]['id'], 'body_parts_id' => $updateArray]);
            !empty($insertData) && Yii::$app->db->createCommand()->batchInsert(PatientBodyParts::tableName(), [
                'patient_user_id', 'body_parts_id', 'status', 'created_at', 'updated_at'
            ], $insertData)->execute();
            // 更新冗余字段
            $body_parts_name = PatientBodyParts::find()
                ->select('GROUP_CONCAT(b.body_parts_name) as body_parts_name')
                ->alias('a')
                ->where([
                    'a.status' => PatientBodyParts::STATUS_ENABLE,
                    'a.patient_user_id' => $patientBodyArray[$body['patient_card_id']]['id']
                ])
                ->leftJoin(BodyParts::tableName() . ' b', 'b.id = a.body_parts_id')
                ->groupBy('a.patient_user_id')
                ->scalar();

            !empty($body_parts_name) && User::updateAll(['patient_body_parts_name' => $body_parts_name, 'updated_at' => time()], ['id' => $patientBodyArray[$body['patient_card_id']]['id']]);
        }
    }

    public function updateClinicNum($params)
    {
        $project_id = $params['project_id'];
        // 查询修改后的 治疗
        $surplusInfo = UserSurplus::find()
            ->select('patient_card_id, help_num, total_num')
            ->where(['patient_card_id' => $params['patient_card_id'], 'project_id' => $project_id, 'clinic_project_id' => $params['clinic_project_id']])
            ->asArray()
            ->one();

        $total_num = $params['total_num'];
        $help_num = $params['help_num'];

        // 如果没有治疗记录 新增一条治疗记录
        if (empty($surplusInfo)) {
            // 获取治疗项目名称
            $clinic_project_name = Project::find()->select('name')->where(['id' => $params['clinic_project_id']])->scalar();
            $surplusModel = New UserSurplus();
            $surplusModel->patient_card_id = $params['patient_card_id'];
            $surplusModel->project_id = $project_id;
            $surplusModel->clinic_project_id = $params['clinic_project_id'];
            $surplusModel->clinic_project_name = $clinic_project_name;
            $surplusModel->saveAndCheckResult();
            $surplusInfo['help_num'] = 0;
            $surplusInfo['total_num'] = 0;
        }

        if ($surplusInfo['help_num'] == $help_num && $total_num == $surplusInfo['total_num']) {
            return true;
        }

        $diff_help = $help_num - $surplusInfo['help_num'];
        $diff_total = $total_num - $surplusInfo['total_num'];
        $commonParams = [
            'project_id' => $project_id,
            'member_id' => Yii::$app->user->identity->member_id,
            'member_name' => Yii::$app->user->identity->member->realname,
            'patient_card_id' => $params['patient_card_id'],
            'clinic_project_id' => $params['clinic_project_id']
        ];

        if ($diff_help >= 0 && $diff_total >= 0) {
            Yii::$app->services->clinicTreatmentPatient->addTreatNum(array_merge($commonParams, [
                'total_num' => $diff_total,
                'help_num' => $diff_help,
            ]));
        } elseif ($diff_help >= 0 && $diff_total <= 0) {

            $diff_help != 0 && Yii::$app->services->clinicTreatmentPatient->addTreatNum(array_merge($commonParams, [
                'total_num' => 0,
                'help_num' => $diff_help,
            ]));

            $diff_total != 0 && Yii::$app->services->clinicTreatmentPatient->refundTreatNum(array_merge($commonParams, [
                'total_num' => abs($diff_total),
                'help_num' => 0,
            ]));

        } elseif ($diff_help <= 0 && $diff_total >= 0) {
            $diff_total != 0 && Yii::$app->services->clinicTreatmentPatient->addTreatNum(array_merge($commonParams, [
                'total_num' => $diff_total,
                'help_num' => 0,
            ]));

            $diff_help != 0 && Yii::$app->services->clinicTreatmentPatient->refundTreatNum(array_merge($commonParams, [
                'total_num' => 0,
                'help_num' => abs($diff_help),
            ]));
        } else {
            Yii::$app->services->clinicTreatmentPatient->refundTreatNum(array_merge($commonParams, [
                'total_num' => abs($diff_total),
                'help_num' => abs($diff_help),
            ]));
        }

        return true;

    }


}
